//
//  BKSelectAnswerTableView.m
//  智能备考学习
//
//  Created by 盛超 on 2018/8/6.
//  Copyright © 2018年 盛超. All rights reserved.
//

#import "BKSelectAnswerTableView.h"
#import "LSListenSelectCell.h"
#import "BKListenAnswerView.h"

@interface BKSelectAnswerTableView ()<UITableViewDelegate,UITableViewDataSource,UIWebViewDelegate>

@property (nonatomic,strong) NSMutableArray *cellHeightArr;
@property (nonatomic,strong) UILabel *numLabel;//标题栏
@property (nonatomic,strong) UIWebView *textWebView;//提干内容部分
@property (nonatomic,strong) UIView *headerView;
@property (nonatomic,strong) UIView *footerView;

@end

@implementation BKSelectAnswerTableView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.dataSource = self;
        self.delegate = self;
        self.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self registerClass:[LSListenSelectCell class] forCellReuseIdentifier:@"LSListenSelectCell"];
//        self.estimatedRowHeight = 50;
//        self.rowHeight = UITableViewAutomaticDimension;
        
        [self createTableHeaderView];
    }
    
    return self;
}


- (UIView*)createFooterView {
    BKListenAnswerView *footerView = [[BKListenAnswerView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 128)];
    NSString *stuAnswer = self.answer;
    NSString *trueAnswer = self.child.ChildAnswer;

    footerView.myAnswer = stuAnswer;
    footerView.tureAnswer = trueAnswer;
    
    return footerView;
}

#pragma mark - UITableDataSource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    LSListenSelectCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LSListenSelectCell" forIndexPath:indexPath];
    
  //  NSNumber *height = self.cellHeightArr[indexPath.row];
 //   cell.textHeight = height.floatValue;
    cell.model = _child.ChildOptionList[indexPath.row];
    cell.optionStyle = SelectOptionWhite;
    cell.userInteractionEnabled = YES;

    if (_answerState==1) {
        cell.userInteractionEnabled = NO;
        NSString *string = [NSString stringWithFormat:@"%c",(int)(indexPath.row+65)];
        NSString *stuAnswer = self.answer;
        NSString *trueAnswer = self.child.ChildAnswer;
        if ([string isEqualToString:stuAnswer] && [stuAnswer isEqualToString:trueAnswer]) {//作答位置和正确位置一致
            cell.optionStyle = SelectOptionGreen;
        } else if ([string isEqualToString:stuAnswer] && ![stuAnswer isEqualToString:trueAnswer]) {
            cell.optionStyle = SelectOptionRed;
        }
    } else if (_answerState==2) {
        cell.userInteractionEnabled = NO;
        NSString *string = [NSString stringWithFormat:@"%c",(int)(indexPath.row+65)];
        NSString *stuAnswer = self.answer;
        NSString *trueAnswer = self.child.ChildAnswer;
        
        if ([string isEqualToString:stuAnswer] && ![stuAnswer isEqualToString:trueAnswer]) {
            cell.optionStyle = SelectOptionRed;
        } else if ([string isEqualToString:trueAnswer]) {
            cell.optionStyle = SelectOptionGreen;
        }
    } else {
        NSString *string = [NSString stringWithFormat:@"%c",(int)(indexPath.row+65)];
        NSString *stuAnswer = self.answer;
        NSLog(@"stuAnswer=%@",self.answer);
        if ([string isEqualToString:stuAnswer]) {
            cell.optionStyle = SelectOptionBlue;
        }
    }
    
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _child.ChildOptionList.count;
}


#pragma mark - UITableDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
//    NSNumber *height = self.cellHeightArr[indexPath.row];
//
//    if (height.floatValue+17<=50) {
//        return 50;
//    }
//
//    return height.floatValue+17;
    LSOption *optionModel = _child.ChildOptionList[indexPath.row];
    
    if (optionModel.cellHeight+17<=50) {
        return 50;
    }
    
    return optionModel.cellHeight+17;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    for (NSInteger i = 0; i<self.child.ChildOptionList.count; i++) {
        NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:i inSection:0];
        LSListenSelectCell *cell = [tableView cellForRowAtIndexPath:newIndexPath];
        if (i==indexPath.row) {
            cell.optionStyle = SelectOptionBlue;//选中
        } else {
            cell.optionStyle = SelectOptionWhite;
        }
    }
    
    NSString *answer = [NSString stringWithFormat:@"%c",(int)(indexPath.row+65)];
    self.answer = answer;
    self.answerBlock(answer);
}


#pragma mark - 根据数据刷新界面
- (void)setChild:(LSChild *)child {
    _child = child;
    
 //   [self getRowHeights];
    
    [self updateUI];
    
    [self reloadData];
    
    if (_answerState==2) {
        self.tableFooterView = [self createFooterView];
    }
}

//计算每个cell高度
//- (void)getRowHeights {
//    self.cellHeightArr = [NSMutableArray array];
//    for (NSInteger i = 0; i<_child.ChildOptionList.count; i++) {
//        NSAttributedString *attr = [_child.ChildOptionList[i].OptionContent showHTMLText:16];
//        CGSize size = [attr boundingRectWithSize:CGSizeMake(kWidth-90, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin context:nil].size;
//        [self.cellHeightArr addObject:@(size.height+1)];
//    }
//}

- (void)updateUI {
    //标题内容
    self.numLabel.text = [NSString stringWithFormat:@"本题包含%ld道小题",_quesModel.TotalItemCount];
    
    //小题题干内容
    if (_child.ChildAsk==nil) {
        _child.ChildAsk = @"";
    }
    NSString *text = [NSString stringWithFormat:@"%ld、%@",_currentIndex,_child.ChildAsk];

    if (_child.ChildStemList.count>0) {
        for (NSInteger i = 0; i<_child.ChildStemList.count; i++) {
            LSStem *stem = _child.ChildStemList[i];
            text = [self joinAsk:text WithStem:stem];
        }
    }
        
    [self.textWebView loadHTMLString:[text webViewHtmlStringWithFont:16.0F] baseURL:nil];
}

- (NSString*)joinAsk:(NSString*)ask WithStem:(LSStem*)stem {
    if (stem.Position==0) {
        ask = [stem.Text stringByAppendingString:ask];
    } else {
        ask = [ask stringByAppendingString:stem.Text];
    }
    return ask;
}

- (void)createTableHeaderView {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 0)];
    self.headerView = headerView;
    UILabel *numlabel = [[UILabel alloc] init];
    self.numLabel = numlabel;
    numlabel.font = [UIFont systemFontOfSize:13.0f];
    [headerView addSubview:numlabel];
    [numlabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(headerView).offset(10);
        make.top.equalTo(headerView).offset(18);
        make.size.mas_equalTo(CGSizeMake(kWidth-20, 13));
    }];
    
    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0,40, kWidth,10)];
    self.textWebView = webView;
    webView.delegate = self;
    webView.scrollView.scrollEnabled = NO;
    [headerView addSubview:webView];
    headerView.height = webView.y +webView.height;
    
    self.tableHeaderView = headerView;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSString *js =[NSString stringWithFormat:@"function imgAutoFit() { \
                   var imgs = document.getElementsByTagName('img'); \
                   for (var i = 0; i < imgs.length; ++i) {\
                   var img = imgs[i];   \
                   img.style.maxWidth = %f;   \
                   } \
                   }",kWidth-20];
    js = [NSString stringWithFormat:js, [UIScreen mainScreen].bounds.size.width ];
    [webView stringByEvaluatingJavaScriptFromString:js];
    [webView stringByEvaluatingJavaScriptFromString:@"imgAutoFit()"];
    // 获取webView的高度
    CGFloat webViewHeight = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] floatValue];
    CGFloat webViewWidth = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollWidth"] floatValue];
    webView.scrollView.contentSize = CGSizeMake(webViewWidth,0);
    webView.scrollView.showsVerticalScrollIndicator = NO;
    webView.scrollView.showsHorizontalScrollIndicator = NO;
    webView.height = webViewHeight+10;
    
    self.headerView.height = self.headerView.height +  webView.height;
    self.tableHeaderView = self.headerView;
}


@end
